<template>
    <view>
        <u-popup v-model="isShowActionSheet" mode="bottom" :closeable="true" height="500px">
            <view v-if="tbGoods">
                <div style="text-align: center; font-size: 20px; margin-top: 20px; margin-bottom: 20px;">
                    请选择
                </div>
                <div style="display: flex; margin-top: 10px; margin-bottom: 10px;">
                    <div>
                        <!--不存在商品颜色-->
                        <div v-if="tbGoods.tbGoodsSpecificationList.length && !tbGoods.tbGoodsColorList.length">
                            <!--未选择规格-->
                            <image :src="tbGoods.thumbnailUrl ? tbGoods.thumbnailUrl + '?imageView2/1/w/300/h/300' : '/static/default-image/goods.jpg'"
                                 alt="图片加载失败" style="height: 150px; width: 150px; display: block;" v-if="!tbGoods.tbGoodsSpecification"/>

                            <!--已选择规则-->
                            <image :src="tbGoods.tbGoodsSpecification.thumbnailUrl ? tbGoods.tbGoodsSpecification.thumbnailUrl + '?imageView2/1/w/300/h/300' : '/static/default-image/goods.jpg'"
                                 alt="图片加载失败" style="height: 150px; width: 150px; display: block;" v-if="tbGoods.tbGoodsSpecification"/>
                        </div>

                        <!--存在商品颜色-->
                        <div v-if="tbGoods.tbGoodsColorList.length">
                            <image :src="tbGoods.thumbnailUrl ? tbGoods.thumbnailUrl + '?imageView2/1/w/300/h/300' : '/static/default-image/goods.jpg'"
                                 alt="图片加载失败" style="height: 150px; width: 150px; display: block;" v-if="!tbGoods.tbGoodsColor"/>

                            <image :src="tbGoods.tbGoodsColor.thumbnailUrl ? tbGoods.tbGoodsColor.thumbnailUrl + '?imageView2/1/w/300/h/300' : '/static/default-image/goods.jpg'"
                                 alt="图片加载失败" style="height: 150px; width: 150px; display: block;" v-if="tbGoods.tbGoodsColor"/>
                        </div>
                    </div>
                    <div>
                        <div style="padding: 10px; margin-top: 10px;">
							<span style="font-size: 20px; color: red; font-weight: bold;">
								￥{{(tbGoods.tbGoodsSpecification && tbGoods.tbGoodsSpecification.price) ? tbGoods.tbGoodsSpecification.price : tbGoods.price}}
							</span>
                            <snap style="font-size: 14px; color: grey; text-decoration: line-through; margin-left: 2px;"
                                  v-if="tbGoods.marketPrice || tbGoods.tbGoodsSpecification && tbGoods.tbGoodsSpecification.marketPrice">
                                ￥{{(tbGoods.tbGoodsSpecification && tbGoods.tbGoodsSpecification.marketPrice) ?
                                tbGoods.tbGoodsSpecification.marketPrice : tbGoods.marketPrice}}
                            </snap>
                        </div>
                    </div>
                </div>
                <div style="padding: 10px; min-height: 185px;">
                    <div>
                        <!--不存在商品颜色-->
                        <div v-if="tbGoods.tbGoodsSpecificationList.length && !tbGoods.tbGoodsColorList.length">
                            <div style="padding: 10px 0px;">商品规格</div>
                            <div>
                                <u-button v-for="(item, index) in tbGoods.tbGoodsSpecificationList" :key="item.id" plain
                                          :custom-style="{color: item.color, margin: '4px'}"
                                          size="mini" @click="selectSpecification(item)" :disabled="item.disabled">{{item.name}}
                                </u-button>
                            </div>
                        </div>

                        <!--存在商品颜色-->
                        <div>
                            <div v-if="tbGoods.tbGoodsColorList.length">
                                <div style="padding: 10px 0px;">商品颜色</div>
                                <div>
                                    <u-button v-for="(item, index) in tbGoods.tbGoodsColorList" :key="item.id" plain
                                              :custom-style="{color: item.color, margin: '4px'}"
                                              size="mini" @click="selectColor(item)" :disabled="item.disabled">{{item.name}}
                                    </u-button>
                                </div>
                            </div>

                            <div v-if="tbGoods.tbGoodsSpecificationList.length && tbGoods.tbGoodsColorList.length">
                                <div style="padding: 10px 0px;">商品规格</div>
                                <div>
                                    <u-button v-for="(item, index) in tbGoods.tbGoodsSpecificationList" :key="item.id" plain
                                              :custom-style="{color: item.color, margin: '4px'}"
                                              size="mini" @click="selectSpecification(item)" :disabled="item.disabled">{{item.name}}
                                    </u-button>
                                </div>
                            </div>
                        </div>

                        <div style="margin-top: 10px; ">
                            <div style="text-align: right; font-size: 12px; color: grey;"
                                 v-if="tbGoods.tbGoodsSpecification && tbGoods.tbGoodsSpecification.stockNumber">
                                库存：{{tbGoods.tbGoodsSpecification.stockNumber}}
                            </div>
                            <div style="display: flex;">
                                <div style="width: 120px;">
                                    购买数量：
                                </div>
                                <div style="right: 5px; position: absolute;">
                                    <u-number-box v-model="tbGoods.quantity" :min="1" :max="999" :long-press="false"></u-number-box>
                                </div>
                            </div>
                        </div>

                        <!--促销活动-->
                        <div style="margin-top: 10px;">
                            <!--不存在商品颜色-->
                            <div v-if="!tbGoods.tbGoodsColorList.length">
                                <!--选择规格颜色时显示对应的促销活动-->
                                <div class="skin-font" v-if="tbGoods.tbGoodsSpecification && tbGoods.tbGoodsSpecification.tbStorePromotion">
                                    <u-divider color="#fa3534" half-width="100%">促销活动</u-divider>
                                    <u-tag class="u-tag-group-line" type="error" mode="plain" style="margin-right: 5px; margin-bottom: 5px;"
                                           v-for="(item, index) of tbGoods.tbGoodsSpecification.tbStorePromotion.typeTextList" :key="item.id"
                                           :text="item['typeText']" @click="showTbStorePromotion(tbGoods.tbGoodsSpecification.tbStorePromotion.id)"/>
                                </div>
                            </div>
                            <!--存在商品颜色-->
                            <div class="skin-font" v-if="tbGoods.tbGoodsColorList.length">
                                <!--同时选择规格颜色时显示对应的促销活动-->
                                <div v-if="tbGoods.tbGoodsSpecification && tbGoods.tbGoodsColor && tbGoods.tbGoodsSpecificationColor.tbStorePromotion">
                                    <u-divider color="#fa3534" half-width="100%">促销活动</u-divider>
                                    <u-tag class="u-tag-group-line" type="error" mode="plain" style="margin-right: 5px; margin-bottom: 5px;"
                                           v-for="(item, index) of tbGoods.tbGoodsSpecificationColor.tbStorePromotion.typeTextList" :key="item.id"
                                           :text="item['typeText']" @click="showTbStorePromotion(tbGoods.tbGoodsSpecificationColor.tbStorePromotion.id)"/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div style="padding: 10px; margin-top: 30px;">
                    <u-button type="error" shape="circle" @click="addShoppingCart">确定</u-button>
                </div>
            </view>
        </u-popup>

        <tbStorePromotion ref="tbStorePromotionRef"></tbStorePromotion>
    </view>
</template>

<script>

    import {TbGoodsService} from "../dev/services/tb-goods.service";
    import {CommonUtil} from "../dev/core/utils/common.util";
    import {TbShoppingCartService} from "../dev/services/tb-shopping-cart.service";
    import tbStorePromotion from '../components/tb-store-promotion.vue'

    export default {
        data() {
            return {
                tbGoods: null,
                isShowActionSheet: false,  // 显示对话框
                immediatelyOrder: false,  // 立即支付,todo 不添加到购物车直接下订单支付
            }
        },
        components: {
            tbStorePromotion
        },
        onLoad() {
            const _self = this
        },
        methods: {
            openGoodsDetailSelect(tbGoods, immediatelyOrder) {
                const _self = this;
                _self.immediatelyOrder = immediatelyOrder;
                if (tbGoods.id) { // 从商品详情打开，完整的商品详情信息
                    _self.tbGoods = Object.assign({}, tbGoods);
                    _self.tbGoods.tbGoodsSpecificationList.forEach(object => {
                        object.color = 'btn-group'
                    });
                    _self.tbGoods.tbGoodsColorList.forEach(object => {
                        object.color = 'btn-group'
                    });

                    _self.setDefaultSelectedSpecificationAndColor();
                    _self.isShowActionSheet = true;
                } else { // 从商品列表打开，tbGoods = {goodsId: ""} 需要从后台获取商品详情信息
                    new TbGoodsService().findGoodsDetail(tbGoods.goodsId).then(detail => {
                        detail.quantity = 1;
                        _self.tbGoods = detail;

                        // 覆盖默认属性
                        _self.tbGoods = Object.assign(_self.tbGoods, {
                            title: tbGoods.tbGoods.title,
                            price: Number(tbGoods.tbGoods.price),
                            marketPrice: Number(tbGoods.tbGoods.marketPrice),
                            specificationId: tbGoods.tbGoods.specificationId,
                            colorId: tbGoods.tbGoods.colorId,
                        });

                        // 如果没有商品颜色，则规格价格为0时，不能选择该规格
                        if (!_self.tbGoods.tbGoodsColorList.length) {
                            _self.tbGoods.tbGoodsSpecificationList.forEach(tbGoodsSpecification => {
                                tbGoodsSpecification.disabled = true;
                                if (tbGoodsSpecification.stockNumber && tbGoodsSpecification.price > 0) {
                                    tbGoodsSpecification.disabled = false
                                }
                            })
                        }

                        _self.tbGoods.tbGoodsSpecificationList.forEach(object => {
                            object.color = 'btn-group'
                        });
                        _self.tbGoods.tbGoodsColorList.forEach(object => {
                            object.color = 'btn-group'
                        });

                        _self.setDefaultSelectedSpecificationAndColor();
                        _self.isShowActionSheet = true;
                    })
                }
            },
            /**
             * 设置默认选中的规则,颜色
             */
            setDefaultSelectedSpecificationAndColor() {
                const _self = this;
                console.log(_self.tbGoods);
                if (_self.tbGoods.specificationId) {
                    _self.tbGoods.tbGoodsSpecificationList.forEach(item => {
                        if (_self.tbGoods.specificationId === item.id) {
                            _self.selectSpecification(item)
                        }
                    });
                }
                if (_self.tbGoods.colorId) {
                    _self.tbGoods.tbGoodsColorList.forEach(item => {
                        if (_self.tbGoods.colorId === item.id) {
                            _self.selectColor(item);
                        }
                    });
                }
            },
            /**
             * 选择规格
             * @param item
             */
            selectSpecification(item) {
                this.tbGoods.tbGoodsSpecificationList.forEach(object => {
                    if (item.id === object.id) {
                        if (object.color !== 'red') {
                            object.color = 'red';
                            this.tbGoods.tbGoodsSpecification = item
                        } else {
                            object.color = 'none';
                            this.tbGoods.tbGoodsSpecification = null
                        }
                    } else {
                        object.color = 'none'
                    }
                })

                // 选中规格
                if (item.color === 'red') {
                    // 禁用一些不能选择的颜色
                    this.tbGoods.tbGoodsColorList.forEach(tbGoodsColor => {
                        tbGoodsColor.disabled = true
                        this.tbGoods.tbGoodsSpecificationColorList.forEach(tbGoodsSpecificationColor => {
                            if (item.id === tbGoodsSpecificationColor.goodsSpecificationId && tbGoodsColor.id ===
                                tbGoodsSpecificationColor.goodsColorId) {
                                if (tbGoodsSpecificationColor.stockNumber && tbGoodsSpecificationColor.price > 0) {
                                    tbGoodsColor.disabled = false
                                }
                            }
                        })
                    })
                } else {
                    this.tbGoods.tbGoodsColorList.forEach(tbGoodsColor => {
                        tbGoodsColor.disabled = false
                    })
                }

                // 如果颜色也选择了，则使用规格颜色里的价格和市场价
                if (this.tbGoods.tbGoodsSpecification && this.tbGoods.tbGoodsColor) {
                    this.tbGoods.tbGoodsSpecificationColorList.forEach(item => {
                        if (this.tbGoods.tbGoodsSpecification.id === item.goodsSpecificationId && this.tbGoods.tbGoodsColor.id === item
                            .goodsColorId) {
                            this.tbGoods.tbGoodsSpecificationColor = item;
                            this.tbGoods.tbGoodsSpecification.stockNumber = item.stockNumber
                            this.tbGoods.tbGoodsSpecification.price = item.price;
                            this.tbGoods.tbGoodsSpecification.marketPrice = item.marketPrice
                        }
                    })
                }

                // 更新对象，否则v-bind:绑定的值不会改变
                this.tbGoods.tbGoodsSpecificationList = [...this.tbGoods.tbGoodsSpecificationList];
                if (this.tbGoods.tbGoodsSpecification) {
                    this.tbGoods.tbGoodsSpecification = Object.assign({}, this.tbGoods.tbGoodsSpecification)
                }
            },

            /**
             * 选择颜色
             * @param item
             */
            selectColor(item) {
                this.tbGoods.tbGoodsColorList.forEach(object => {
                    if (item.id === object.id) {
                        if (object.color !== 'red') {
                            object.color = 'red'
                            this.tbGoods.tbGoodsColor = item
                        } else {
                            object.color = 'none'
                            this.tbGoods.tbGoodsColor = null
                        }
                    } else {
                        object.color = 'none'
                    }
                })

                // 选中颜色
                if (item.color === 'red') {
                    // 禁用一些不能选择的规格
                    this.tbGoods.tbGoodsSpecificationList.forEach(tbGoodsSpecification => {
                        tbGoodsSpecification.disabled = true
                        this.tbGoods.tbGoodsSpecificationColorList.forEach(tbGoodsSpecificationColor => {
                            if (item.id === tbGoodsSpecificationColor.goodsColorId && tbGoodsSpecification.id ===
                                tbGoodsSpecificationColor.goodsSpecificationId) {
                                if (tbGoodsSpecificationColor.stockNumber && tbGoodsSpecificationColor.price > 0) {
                                    tbGoodsSpecification.disabled = false
                                }
                            }
                        })
                    })
                } else {
                    this.tbGoods.tbGoodsSpecificationList.forEach(tbGoodsSpecification => {
                        tbGoodsSpecification.disabled = false
                    })
                }

                // 如果规格颜色都选择了，则使用规格颜色里的价格和市场价
                if (this.tbGoods.tbGoodsSpecification && this.tbGoods.tbGoodsColor) {
                    this.tbGoods.tbGoodsSpecificationColorList.forEach(item => {
                        if (this.tbGoods.tbGoodsSpecification.id === item.goodsSpecificationId && this.tbGoods.tbGoodsColor.id === item
                            .goodsColorId) {
                            this.tbGoods.tbGoodsSpecificationColor = item
                            this.tbGoods.tbGoodsSpecification.stockNumber = item.stockNumber
                            this.tbGoods.tbGoodsSpecification.price = item.price
                            this.tbGoods.tbGoodsSpecification.marketPrice = item.marketPrice
                        }
                    })
                }

                // 更新对象，否则v-bind:绑定的值不会改变
                this.tbGoods.tbGoodsColorList = [...this.tbGoods.tbGoodsColorList]
                if (this.tbGoods.tbGoodsColor) {
                    this.tbGoods.tbGoodsColor = Object.assign({}, this.tbGoods.tbGoodsColor)
                }
            },

            /**
             * 显示促销活动
             */
            showTbStorePromotion(id) {
                this.$refs.tbStorePromotionRef.openTbStorePromotion(id);
            },

            /**
             * 添加购物车
             */
            addShoppingCart() {
                const _self = this;
                console.log(this.tbGoods.tbGoodsSpecification);
                console.log(this.tbGoods.tbGoodsColor);
                if (this.tbGoods.tbGoodsSpecificationList.length && !this.tbGoods.tbGoodsSpecification) {
                    uni.showToast({
                        title: '请选择商品规格',
                        icon: 'none',
                    });
                    return
                }

                if (this.tbGoods.tbGoodsColorList.length && !this.tbGoods.tbGoodsColor) {
                    uni.showToast({
                        title: '请选择商品颜色',
                        icon: 'none',
                    });
                    return
                }

                // 校验下单数量，满足库存量的条件下一次最多可以下999，防止样式问题。
                if (!this.tbGoods.tbGoodsColorList.length) {
                    let flag = false
                    this.tbGoods.tbGoodsSpecificationList.forEach(item => {
                        if (item.id === this.tbGoods.tbGoodsSpecification.id) {
                            if (this.tbGoods.quantity > item.stockNumber) {
                                this.tbGoods.quantity = item.stockNumber
                                uni.showModal({
                                    title: '提示',
                                    content: '商品库存不足，已调整为最大可下数量，请核实后重新添加。',
                                    showCancel: false
                                });
                                flag = true
                            }
                        }
                    });
                    if (flag) {
                        return
                    }
                } else {
                    let flag = false;
                    this.tbGoods.tbGoodsSpecificationColorList.forEach(item => {
                        if (this.tbGoods.tbGoodsSpecification.id === item.goodsSpecificationId && this.tbGoods.tbGoodsColor.id === item
                            .goodsColorId) {
                            if (this.tbGoods.quantity > item.stockNumber) {
                                this.tbGoods.quantity = item.stockNumber
                                uni.showModal({
                                    title: '提示',
                                    content: '商品库存不足，已调整为最大可下数量，请核实后重新添加。',
                                    showCancel: false
                                });
                                flag = true
                            }
                        }
                    });
                    if (flag) {
                        return
                    }
                }

                // 如果店铺是餐饮模式，先校验关联的餐饮号是否在店铺设置的餐饮号范围内
                if (this.tbGoods.tbStore.saleMode === '2') {
                    // 如果绑定的餐饮号无效，则不能前往确认订单页面
                    if (`,${this.tbGoods.tbStore.orderSequenceNumbers},`.indexOf(`,${this.globalVariable.orderSequenceNumber},`) === -1) {
                        CommonUtil.alert('请先扫码获取餐饮号');
                        return;
                    }
                }

                new TbShoppingCartService().saveTbShoppingCart({
                    communityId: this.globalVariable.userInfo.tbCommunity.id,
                    userId: this.globalVariable.userInfo.id,
                    storeId: this.tbGoods.storeId,
                    goodsId: this.tbGoods.id,
                    goodsSpecificationId: this.tbGoods.tbGoodsSpecification.id,
                    goodsColorId: this.tbGoods.tbGoodsColor ? this.tbGoods.tbGoodsColor.id : null,
                    quantity: this.tbGoods.quantity,
                    type: !this.immediatelyOrder ? '0' : '1'  // 类型：0-加入购物车，1-立即购买
                }).then(result => {
                    // 加入购物车
                    if (!this.immediatelyOrder) {
                        CommonUtil.toast('添加购物车成功')
                        _self.$emit('addedEmit');
                    } else { // 立即下单

                        let shoppingCartIds = [result.id];

                        // 将勾选的商品保存在全局变量中，在确定订单页面直接获取
                        if (this.tbGoods.tbStore.saleMode === '0') { // 物流模式
                            uni.navigateTo({
                                url: `/pages/sub/sub1-tabs/tabs/shopping-cart/order-add/index?shoppingCartIds=${shoppingCartIds.join(',')}`
                            })
                        } else if (this.tbGoods.tbStore.saleMode === '1') { // 消费券模式
                            uni.navigateTo({
                                url: `/pages/sub/sub1-tabs/tabs/shopping-cart/consumer-voucher-add/index?shoppingCartIds=${shoppingCartIds.join(',')}`
                            })
                        } else if (this.tbGoods.tbStore.saleMode === '2') { // 餐饮店模式
                            uni.navigateTo({
                                url: `/pages/sub/sub1-tabs/tabs/shopping-cart/eatery-order-add/index?shoppingCartIds=${shoppingCartIds.join(',')}`
                            })
                        }
                    }

                    _self.isShowActionSheet = false;
                    _self.tbGoods = null;
                });
            }
        }
    }
</script>

<style lang="scss" scoped>
</style>
